<?php
/**
 * 店铺管理模块微站定义
 *
 * @author 橙橙同学
 * @url 
 */
defined('IN_IA') or exit('Access Denied');

class Orange_storemanageModuleSite extends WeModuleSite {

	public function doMobileStoremanageentry() {
		//这个操作被定义用来呈现 功能封面
	}

	public function doWebStoreSort($where = '')
    {
        global $_GPC,$_W;
        $op = $_GPC['op']?$_GPC['op']:'display';
        $return = array(
            'errCode'=>0,
            'msg'=>''
        );

        if($_GPC['token'] == $_W['token'] && $_GPC['submit']!=''){
            //搜索
            $value = trim($_GPC['keyword']);
            $where = "and value like '%{$value}%'";
        }else{
            $where = '';
        }

        switch ($op){

            case 'add':
                if (checksubmit() && $_W['token'] == $_GPC['token']) {

                    if(empty($_GPC['value']) || empty($_GPC['type'])){
                      message('名称或类型不能为空','referer','error');
//                        $return = array(
//                            'errCode'=>0,
//                            'msg'=>'名称或类型不能为空'
//                        );
                    }else{
                        $data = array(
                            'value'=>$_GPC['value'],
                            'type'=>intval($_GPC['type']),
                            'create_time'=>time(),
                            'uniacid'=>intval($_W['uniacid']),
//                           分类的所属
                            'furthersort_id'=>intval($_GPC['furthersort'])
                        );
                        $res = pdo_insert('storemanage_sorts',$data);

                        if($res){
//                            $return = array(
//                                'errCode'=>0,
//                                'msg'=>'添加成功'
//                            );
                          message('添加成功','referer','success');
                        }else{
//                            $return = array(
//                                'errCode'=>0,
//                                'msg'=>'添加失败'
//                            );
                        message('添加失败，请重试','referer','error');
                        }
                    }
                    echo json_encode($return);
                }
                break;
            case 'storebrandmanage':
                $pindex = max(1, intval($_GPC["page"]));
                $psize = 5;
                $list = pdo_fetchall("SELECT * FROM " . tablename('storemanage_sorts') . " 
                WHERE `uniacid`=:uniacid and status!=-1 and `type`=:type  {$where} ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, array(':uniacid'=>$_W['uniacid'],':type'=>1));
                $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('storemanage_sorts') . " 
                WHERE uniacid = '{$_W['uniacid']}' and status!=-1 and `type`=1 {$where}");
                $pager = pagination($total, $pindex, $psize, $url = '', $context = array('before' => 2, 'after' => 2, 'ajaxcallback' => ''));
                break;
            case 'storepositionmanage':
                $pindex = max(1, intval($_GPC["page"]));
                $psize = 5;
                $list = pdo_fetchall("SELECT * FROM " . tablename('storemanage_sorts') . " 
                WHERE `uniacid`=:uniacid and status!=-1 and `type`=:type {$where} ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, array(':uniacid'=>$_W['uniacid'],':type'=>2));
                $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('storemanage_sorts') . " 
                WHERE uniacid = '{$_W['uniacid']}' and status!=-1 and `type`=2 {$where}");
                $pager = pagination($total, $pindex, $psize, $url = '', $context = array('before' => 2, 'after' => 2, 'ajaxcallback' => ''));
                break;

            case 'storenumbermanage':
                $pindex = max(1, intval($_GPC["page"]));
                $psize = 5;
                $list = pdo_fetchall("SELECT * FROM " . tablename('storemanage_sorts') . " 
                WHERE `uniacid`=:uniacid and status!=-1 and `type`=:type {$where} ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, array(':uniacid'=>$_W['uniacid'],':type'=>3));
                $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('storemanage_sorts') . " 
                WHERE uniacid = '{$_W['uniacid']}' and status!=-1 and `type`=3 {$where}");
                $pager = pagination($total, $pindex, $psize, $url = '', $context = array('before' => 2, 'after' => 2, 'ajaxcallback' => ''));
                break;

            default:

        }

        include $this->template('storestort/sortmanage');
    }


    public function doWebAttrManage()
    {

        global $_GPC,$_W;
        $op = $_GPC['op']?$_GPC['op']:'display';
        $return = array(
            'errCode'=>0,
            'msg'=>''
        );

        if($_GPC['token'] == $_W['token'] && $_GPC['submit']!=''){
            //搜索
            $value = trim($_GPC['keyword']);
            $where = "and value like '%{$value}%'";
        }else{
            $where = '';
        }

        switch ($op){
            case 'display':
                $pindex = max(1, intval($_GPC["page"]));
                $psize = 5;
                $list = pdo_fetchall("SELECT * FROM " . tablename('storemanage_attr') . " 
                WHERE `uniacid`=:uniacid {$where} ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, array(':uniacid'=>$_W['uniacid']));
                $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('storemanage_attr') . " 
                WHERE uniacid = '{$_W['uniacid']}' {$where}");
                $pager = pagination($total, $pindex, $psize, $url = '', $context = array('before' => 2, 'after' => 2, 'ajaxcallback' => ''));
                break;
            case 'add':
                if ($_W['isajax'] && $_W['ispost']) {

                    if (empty($_GPC['value']) || empty($_GPC['key'])) {
//                        message('名称或类型不能为空','referer','error');
                        $return = array(
                            'errCode' => -1,
                            'msg' => '不能为空'
                        );
                    } else {
                        $attrInfo = pdo_fetch("SELECT * FROM " . tablename('storemanage_attr') . " 
                 WHERE `uniacid`=:uniacid  and `value`=:value", array(':uniacid' => $_W['uniacid'], ':value' => $_GPC['value']));

                        if (empty($attrInfo)) {
                            $data = array(
                                'key'=>$_GPC['key'],
                                'value' => $_GPC['value'],
                                'create_time' => time(),
                                'uniacid' => intval($_W['uniacid']),
                            );
                            $res = pdo_insert('storemanage_attr', $data);

                            if ($res) {
                                $return = array(
                                    'errCode' => 0,
                                    'msg' => '添加成功'
                                );
//                            message('添加成功','referer','success');
                            } else {
                                $return = array(
                                    'errCode' => -1,
                                    'msg' => '添加失败'
                                );
//                            message('添加失败，请重试','referer','error');
                            }
                        } else {
                            $return = array(
                                'errCode' => -1,
                                'msg' => '添加失败，属性名已存在'
                            );
                        }
                    }
                    echo json_encode($return);
                    exit();
                }
                break;
                case 'edit':
                    if ($_W['isajax'] && $_W['ispost']) {
                        $value = $_GPC['value'];
                        $id = $_GPC['id'];
                        $data = array('value' => $value);
                        $res = pdo_update('storemanage_attr', $data, array('id' => $id));
                        if ($res) {
                            $return['msg'] = '更新成功';
                        } else {
                            $return['errCode'] = -1;
                            $return['msg'] = '更新失败';
                        }
                        echo json_encode($return);
                        exit();
                    }
                    break;
            case "delete":
                if ($_W['isajax'] && $_W['ispost']) {
                    $id = $_GPC['id'];
                    $res = pdo_delete('storemanage_attr', array('id' => $id));
                    if ($res) {
                        $return['msg'] = '删除成功';
                    } else {
                        $return['errCode'] = -1;
                        $return['msg'] = '更新失败';
                    }
                    echo json_encode($return);
                    exit();
                }
                    break;
            default:

        }
        include $this->template('attrmanage/attrmanage');
    }







    public function doWebStorePositionManage()
    {
        global $_GPC,$_W;
        $op = $_GPC['op']?$_GPC['op']:'display';
        $return = array(
            'errCode'=>0,
            'msg'=>''
        );
        //获取id
        $type = 2;
        $id = $_GPC['id'];
        switch ($op){
            case 'delete':
                $data = array('status'=>-1);
                $res = pdo_update('storemanage_sorts',$data,array('id'=>$id,'type'=>$type));
//                $res = pdo_delete('storemanage_sorts',array('id'=>$id,'type'=>$type));
                if($res){
                    $return['msg'] = '删除成功';
                }else{
                    $return['errCode'] = -1;
                    $return['msg'] = '删除失败';
                }
                echo json_encode($return);
                exit();
                break;
            case 'change_status':
                $status = $_GPC['status'];
                $data = array('status'=>$status);
                $res = pdo_update('storemanage_sorts',$data,array('id'=>$id,'type'=>$type));
                if($res){
                    $return['msg'] = '更改状态成功';
                }else{
                    $return['errCode'] = -1;
                    $return['msg'] = '更改状态失败';
                }
                echo json_encode($return);
                exit();
                break;
            case 'edit':
                $value = $_GPC['value'];
                $data = array('value'=>$value);
                $res = pdo_update('storemanage_sorts',$data,array('id'=>$id,'type'=>$type));
                if($res){
                    $return['msg'] = '更新成功';
                }else{
                    $return['errCode'] = -1;
                    $return['msg'] = '更新失败';
                }
                echo json_encode($return);
                exit();
                break;
        }
        include $this->template('storestort/sortmanage');
    }


    /**
     * @param string $where
     * @return array
     * @author:橙橙同学
     * @func:获取店铺列表
     */
    public function getStoreList($where = ''){

        global $_W,$_GPC;
        load()->func('tpl');
        $pindex = max(1, intval($_GPC["page"]));
        $psize = 5;
        $list = pdo_fetchall("SELECT * FROM " . tablename('storemanage_store') . " 
        WHERE `uniacid`=:uniacid {$where} ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, array(':uniacid'=>$_W['uniacid']));

        $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('storemanage_store') . " 
        WHERE uniacid = '{$_W['uniacid']}' {$where}");

        $pager = pagination($total, $pindex, $psize, $url = '', $context = array('before' => 2, 'after' => 2, 'ajaxcallback' => ''));
        return array(
            'list'=>$list,
            'pager'=>$pager
        );
    }

    public function getStoreAttrList($store_id)
    {
        global $_W;

        if(!empty($store_id)){

            //注意这里的status=1 代表是店铺正常的标签
            $attrids = pdo_fetchall("SELECT attr_id FROM " . tablename('storemanage_attrstore') . " 
            WHERE `uniacid`=:uniacid and `store_id`=:store_id and status=1", array(':uniacid'=>$_W['uniacid'],':store_id'=>$store_id),'attr_id');

            $attrIdsFormat = array();
            foreach ($attrids as $key=>$value)
            {
                $attrIdsFormat[] = $value['attr_id'];
            }

            if(!empty($attrIdsFormat))
            {
                $attrList = pdo_fetchall("SELECT * FROM " . tablename('storemanage_attr') . " 
                 WHERE `uniacid`=:uniacid and `id` in (".implode(',',$attrIdsFormat).") ", array(':uniacid'=>$_W['uniacid']));
                if(!empty($attrList)){
                    $res = $attrList;
                }
                else{
                    $res = '';
                }
            }
            else{
                $res = '';
            }

        }
        else{
            $res = '';
        }
        return $res;
    }



    /**
     * @author:橙橙同学
     * @func:编辑文章店铺接口
     */
    public function doWebUpdateArticleStore()
    {
        global $_W,$_GPC;
        if($_W['isajax'] && $_W['ispost'])
        {
            $store_id = $_GPC['store_id'];
            $article_id = $_GPC['article_id'];

            if(!empty($store_id) && !empty($article_id))
            {
                //查询
                $storeInfo = pdo_fetch("select * from ".tablename('storemanage_storearticle')." where `uniacid`=:uniacid and `store_id`=:store_id and `article_id`=:article_id 
                ",array(":uniacid"=>$_W['uniacid'],":store_id"=>$store_id,":article_id"=>$article_id));

                //如果此属性对于此店铺而言不为空 那么是更新操作
                if(!empty($storeInfo))
                {
                    $data = array(
                        'status'=>!$storeInfo['status']
                    );
                    $updateRes = pdo_update('storemanage_storearticle',$data,array('store_id'=>$store_id,'article_id'=>$article_id));
                    if($updateRes){
                        $return = array('msg'=>'改变文章店铺成功,请点击发布提交','errCode'=>0,'data'=>'');
                    }else{
                        $return = array('msg'=>'改变文章店铺失败','errCode'=>-1,'data'=>'');
                    }

                }else{
                    //插入操作
                    $data = array(
                        'store_id'=>$store_id,
                        'article_id'=>$article_id,
                        'uniacid'=>$_W['uniacid']
                    );

                    $insertRes = pdo_insert('storemanage_storearticle',$data);
                    if($insertRes)
                    {
                        $return = array('msg'=>'新增文章店铺成功，请点击发布提交','errCode'=>0,'data'=>'');
                    }
                    else{
                        $return = array('msg'=>'新增文章店铺失败','errCode'=>-1,'data'=>'');
                    }
                }
            }
            else{
                $return = array('msg'=>'非法请求','errCode'=>-1,'data'=>'');
            }
            echo json_encode($return);
        }

    }
    /**
     * @author:橙橙同学
     * @func:编辑店铺属性接口
     */
    public function doWebUpdateStoreAttr()
    {
        global $_W,$_GPC;
        if($_W['isajax'] && $_W['ispost'])
        {
            $store_id = $_GPC['store_id'];
            $attr_id = $_GPC['attr_id'];

            if(!empty($store_id) && !empty($attr_id))
            {

                //查询
                $attrInfo = pdo_fetch("select * from ".tablename('storemanage_attrstore')." where `uniacid`=:uniacid and `store_id`=:store_id and `attr_id`=:attr_id 
                ",array(":uniacid"=>$_W['uniacid'],":store_id"=>$store_id,":attr_id"=>$attr_id));

                //如果此属性对于此店铺而言不为空 那么是更新操作
                if(!empty($attrInfo))
                {
                    $data = array(
                        'status'=>!$attrInfo['status']
                    );
                    $updateRes = pdo_update('storemanage_attrstore',$data,array('store_id'=>$store_id,'attr_id'=>$attr_id));

                    if($updateRes){
                        $return = array('msg'=>'改变店铺属性成功','errCode'=>0,'data'=>'');
                    }else{
                        $return = array('msg'=>'改变店铺属性失败','errCode'=>-1,'data'=>'');
                    }

                }else{
                    //插入操作
                    $data = array(
                        'store_id'=>$store_id,
                        'attr_id'=>$attr_id,
                        'uniacid'=>$_W['uniacid']
                    );

                    $insertRes = pdo_insert('storemanage_attrstore',$data);

                    if($insertRes)
                    {
                        $return = array('msg'=>'新增店铺属性成功','errCode'=>0,'data'=>'');
                    }
                    else{
                        $return = array('msg'=>'新增属性失败','errCode'=>-1,'data'=>'');
                    }
                }
            }
            else{
                $return = array('msg'=>'非法请求','errCode'=>-1,'data'=>'');
            }
            echo json_encode($return);
        }

    }
    public function getCheckedBox($id,$ids)
    {
        if(!empty($id) && is_array($ids)){
            if(in_array($id,$ids)){
                echo "checked";
            }
        }
    }

    /**
     * @author:橙橙同学
     * @func:编辑店铺
     */
    public function doWebEditStore(){
        global $_GPC, $_W;
        load()->func('tpl');
        //获取创建卡时数据库创建的主键id
        $store_id = $_GPC['update_store_id'];
        //根据id查询创建会员卡的信息

        $attrs = pdo_fetchall('select * from '.tablename('storemanage_attr').'where uniacid=:uniacid ',array(':uniacid'=>$_W['uniacid']));

        $storeAttrs = array();
        $storeAttrs = $this->getStoreAttrList($store_id);
        if(!empty($storeAttrs))
        {
            foreach ($storeAttrs as $key=>$value)
            {
                $storeAttrIds[] = $value['id'];
            }
        }

        $row = pdo_fetch("SELECT * FROM " . tablename('storemanage_store') . " 
        WHERE `id`=:store_id", array(':store_id'=>$store_id));

        include $this->template('storemanage/edit');
    }


	public function doWebStoremanage() {

        global $_GPC, $_W;
        $op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
        if($op == 'display'){

            if($_GPC['token'] == $_W['token'] && $_GPC['submit']!=''){
                //搜索
                $value = trim($_GPC['storename']);
                $where = "and storename like '%{$value}%'";
                $return = $this->getStoreList($where);

            }else{
                $return = $this->getStoreList();
            }
            $list = $return['list'];
            $pager = $return['pager'];
        }
        include $this->template('storemanage/display');
		//这个操作被定义用来呈现 管理中心导航菜单
	}


    /**
     * @param $storename
     * @return bool
     * @author:橙橙同学
     * @func:检查店铺
     */
	public function doWebcheckStore($storename = ''){
	    global $_GPC;
	    $storename = $_POST['storename'];

	    if(isset($_GPC['update_store_id']) && $_GPC['update_store_id']!=''){
            $store = pdo_fetch('select * from '.tablename('storemanage_store').'where storename=:storename and id!=:store_id',
                array(
                    'storename'=>$storename,
                    'store_id'=>$_GPC['update_store_id']
                )
            );
           
        }else{
            $store = pdo_fetch('select * from '.tablename('storemanage_store').'where storename=:storename',array('storename'=>$storename));
        }
	    if(!empty($store)){
	        $return = array('message'=>'该店铺名已存在，无法正常提交，请核对后重新填写','errorCode'=>100);
	        echo json_encode($return);
        }else{
            $return = array('message'=>'店铺名合法请继续填写','errorCode'=>0);
            echo json_encode($return);
        }
    }

    public function getFurtherSortById($id){
	    global $_W;
	    $store = pdo_fetch('select * from '.tablename('storemanage_furthersorts').'where id=:id and uniacid=:uniacid',array(':id'=>$id,':uniacid'=>$_W['uniacid']));
        if($store){
            return $store['value'];
        }else{
            return '无';
        }
    }

    /**
     * @author:橙橙同学
     * @func:添加店铺
     */
    public function doWebAddstore() {
        global $_GPC,$_W;

        $attrs = pdo_fetchall('select * from '.tablename('storemanage_attr').'where uniacid=:uniacid ',array(':uniacid'=>$_W['uniacid']));

        if(checksubmit('submit')){
            $store = pdo_fetch('select * from '.tablename('storemanage_store').'where storename=:storename',array('storename'=>$_GPC['storename']));
            $data['storename'] = trim($_GPC['storename']);
            $data['storepic'] = trim($_GPC['storepic']);
            $data['create_time'] = time();
            $data['uniacid'] = $_W['uniacid'];
            $data['storedesc'] = $_GPC['storedesc'];
            $storeAttrArray = $_GPC['storeattr'];

            if(!$_GPC['update_store_id']){
                try {
                    pdo_begin();

                    $insert = pdo_insert('storemanage_store', $data);
                    if($insert)
                    {
                        //取得store_id主键 作为关联表的外键
                        $insert_storeid = pdo_insertid();

                        if(!empty($storeAttrArray))
                        {
                            foreach ($storeAttrArray as $key=>$value)
                            {
                                $attrStorData = array(
                                    'store_id'=>$insert_storeid,
                                    'attr_id'=>intval($value),
                                    'uniacid'=>$_W['uniacid']
                                );
                                $insert_storeattr = pdo_insert('storemanage_attrstore',$attrStorData);
                                if(!$insert_storeattr){
                                    throw new Exception('数据插入失败');
                                }
                            }
                        }

                    }else{
                        throw new Exception('数据插入失败');
                    }
                    pdo_commit();
                    message('添加店铺成功','referer','success');
                } catch (Exception $e) {
                    pdo_rollback();
                    message('添加店铺失败','referer','error');
                }

            }else{
                $res = pdo_update('storemanage_store', $data,array('id'=>$_GPC['update_store_id']));

                if($res){
                    message('编辑成功','referer','success');
                }else{
                    message('编辑失败','referer','error');
                }
            }
        }

        include $this->template('storemanage/storeadd');
        //这个操作被定义用来呈现 管理中心导航菜单
    }





	public function doMobileIndexnav() {
		//这个操作被定义用来呈现 微站首页导航图标
	}
	public function doMobilePersonalnav() {
		//这个操作被定义用来呈现 微站个人中心导航
	}
	public function doMobileQknav() {
		//这个操作被定义用来呈现 微站快捷功能导航
	}
	public function doWebSinglefun() {
		//这个操作被定义用来呈现 微站独立功能
	}

}